package cn.dankal.flyaudio.adapter;

import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.DrawableRes;
import cn.dankal.basiclib.base.recyclerview.BaseRecyclerViewAdapter;
import cn.dankal.basiclib.base.recyclerview.BaseRecyclerViewHolder;
import cn.dankal.basiclib.util.SharePreferenceManager;
import cn.dankal.basiclib.util.image.PicUtils;
import cn.dankal.flyaudio.FlyApplication;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.entity.Event;
import cn.dankal.flyaudio.entity.EventType;
import cn.dankal.flyaudio.friend.ChatActivity;
import cn.dankal.flyaudio.friend.utils.DialogCreator;
import cn.dankal.flyaudio.friend.utils.HandleResponseCode;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.content.TextContent;
import cn.jpush.im.android.api.enums.ConversationType;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.GroupInfo;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.android.api.options.MessageSendingOptions;
import cn.jpush.im.api.BasicCallback;

public class GroupListAdapter2 extends BaseRecyclerViewAdapter<GroupInfo> {

    private String groupName;
    private boolean mIsForward;
    private int mWidth;
    private boolean mBusiness;
    private Dialog mLoadingDialog;
    private Dialog mDialog;
    private Map<Long, String> mGroupName = new HashMap<>();
    private String mUserName;
    private String mAppKey;
    private String mAvatarPath;

    public void initParams(boolean isFromForward, int width, boolean isBusinessCard, String userName, String appKey, String path) {
        this.mIsForward = isFromForward;
        this.mWidth = width;
        this.mBusiness = isBusinessCard;
        this.mUserName = userName;
        this.mAppKey = appKey;
        this.mAvatarPath = path;
    }

    @Override
    protected int getLayoutResId(int viewType) {
        return R.layout.item_group_list;
    }

    @Override
    protected BaseRecyclerViewHolder getViewHolder(ViewGroup parent, View rootView, int viewType) {
        return new ViewHolder(rootView);
    }

    private String getGroupName(List<UserInfo> groupMembers, StringBuilder builder) {
        for (UserInfo info : groupMembers) {
            String noteName = info.getDisplayName();
            builder.append(noteName);
            builder.append(",");
        }

        return builder.substring(0, builder.lastIndexOf(","));
    }

    public class ViewHolder extends BaseRecyclerViewHolder<GroupInfo> {

        public ViewHolder(View itemView) {
            super(itemView);
        }

        @Override
        public void onBindData(GroupInfo data, int position) {
            if (TextUtils.isEmpty(data.getGroupName())) {
                //Conversation groupConversation = JMessageClient.getGroupConversation(groupId);
                //群组名是null的话,手动拿出5个名字拼接
                List<UserInfo> groupMembers = data.getGroupMembers();

                StringBuilder builder = new StringBuilder();
                if (groupMembers.size() <= 5) {
                    groupName = getGroupName(groupMembers, builder);
                } else {
                    List<UserInfo> newGroupMember = groupMembers.subList(0, 5);
                    groupName = getGroupName(newGroupMember, builder);
                }
            } else {
                groupName = data.getGroupName();
            }

            mGroupName.put(data.getGroupID(), groupName);
            setText(R.id.group_name, groupName);
            int newNum = SharePreferenceManager.getCachedNewGroupInvateNumByGid(data.getGroupID());
            setVisibility(R.id.tv_num,newNum > 0);
            setText(R.id.tv_num,""+newNum);

            ImageView avatar = itemView.findViewById(R.id.group_iv);
            PicUtils.loadAvatarByGroup(data.getAvatarFile(), avatar);
            itemView.findViewById(R.id.item).setOnClickListener(null);
            if (mIsForward) {
                itemView.findViewById(R.id.group_ll).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DialogCreator.createForwardMsg(context, mWidth, false, null, data, mGroupName.get(data.getGroupID()), null);
                    }
                });
            } else if (mBusiness) {
                itemView.findViewById(R.id.group_ll).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        View.OnClickListener listener = new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                switch (v.getId()) {
                                    case R.id.btn_cancel:
                                        mDialog.dismiss();
                                        break;
                                    case R.id.btn_sure:
                                        mDialog.dismiss();
                                        mLoadingDialog = DialogCreator.createLoadingDialog(context,
                                                context.getString(R.string.btn_send));
                                        mLoadingDialog.show();
                                        //把名片的userName和appKey通过extra发送给对方
                                        TextContent content = new TextContent("推荐了一张名片");
                                        content.setStringExtra("userName", mUserName);
                                        content.setStringExtra("appKey", mAppKey);
                                        content.setStringExtra("businessCard", "businessCard");

                                        Conversation conversation = JMessageClient.getGroupConversation(data.getGroupID());
                                        if (conversation == null) {
                                            conversation = Conversation.createGroupConversation(data.getGroupID());
                                            EventBus.getDefault().post(new Event.Builder()
                                                    .setType(EventType.createConversation)
                                                    .setConversation(conversation)
                                                    .build());
                                        }
                                        Message textMessage = conversation.createSendMessage(content);
                                        MessageSendingOptions options = new MessageSendingOptions();
                                        options.setNeedReadReceipt(true);
                                        JMessageClient.sendMessage(textMessage, options);
                                        textMessage.setOnSendCompleteCallback(new BasicCallback() {
                                            @Override
                                            public void gotResult(int i, String s) {
                                                if (i == 0) {
                                                    Toast.makeText(context, "发送成功", Toast.LENGTH_SHORT).show();
                                                } else {
                                                    HandleResponseCode.onHandle(context, i, false);
                                                }
                                            }
                                        });
                                        mLoadingDialog.dismiss();
                                        break;
                                }
                            }
                        };
                        mDialog = DialogCreator.createBusinessCardDialog(context, listener, data.getGroupName(), mUserName, mAvatarPath);
                        mDialog.getWindow().setLayout((int) (0.8 * mWidth), WindowManager.LayoutParams.WRAP_CONTENT);
                        mDialog.show();
                    }
                });
            } else {
                itemView.findViewById(R.id.item).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Conversation groupConversation = JMessageClient.getGroupConversation(data.getGroupID());
                        if (groupConversation == null) {
                            groupConversation = Conversation.createGroupConversation(data.getGroupID());
                            EventBus.getDefault().post(new Event.Builder()
                                    .setType(EventType.createConversation)
                                    .setConversation(groupConversation)
                                    .build());
                        }

                        SharePreferenceManager.removeCachedNewGroupInvateNumByGid(data.getGroupID());

                        Intent intent = new Intent(context, ChatActivity.class);
                        intent.putExtra(FlyApplication.CONV_TITLE, mGroupName.get(data.getGroupID()));
                        intent.putExtra(FlyApplication.GROUP_ID, data.getGroupID());
                        context.startActivity(intent);

                    }
                });
            }
        }
    }

    private String getResourcesUri(@DrawableRes int id) {
        Resources resources = context.getResources();
        String uriPath = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
                resources.getResourcePackageName(id) + "/" +
                resources.getResourceTypeName(id) + "/" +
                resources.getResourceEntryName(id);
        return uriPath;
    }
}
